<?php

namespace MoChat\App\Home\Action;

use Hyperf\DbConnection\Db;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Sales\Constants\SalesTaskStatusCode;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Contract\SalesClientTaskEmployeeContract;
use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;

/**
 * 成单折现
 * @Controller
 */
class DealOrder extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * 处理时间
     * @param $startTime
     * @param $endTime
     * @return array
     */
    private function processingDate($startTime, $endTime): array
    {
        $start = strtotime($startTime);
        $end = strtotime($endTime);
        $timeRage = [];
        while (true) {
            if ($start > $end) {
                break;
            }
            $month = date('Y-m', $start);
            $timeRage[] = $month;
            $start = strtotime('+1 month', $start);
        }
        return $timeRage;
    }

    private function processingData($timeRage, $orders, $users): array
    {
        $orders = empty($orders) ? [] : array_column($orders, null, 'month');
        $users = empty($users) ? [] : array_column($users, null, 'month');
        $data = [];
        foreach ($timeRage as $value) {
            $data['time'][] = $value;
            if (isset($orders[$value])) {
                $data['order_value'][] = $orders[$value]->count ?? 0;
            } else {
                $data['order_value'][] = 0;
            }
            if (isset($users[$value])) {
                $data['client_value'][] = $users[$value]->count ?? 0;
            } else {
                $data['client_value'][] = 0;
            }
        }
        return $data;
    }


    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/home/dealOrder", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $startTime = date('Y-m-d', strtotime('-11 month', time()));
        $endTime = date('Y-m-d');
        $datStartTime = "2023-01-01 00:00:00";
        if (strtotime($datStartTime) > strtotime($startTime)) {
            $startTime = $datStartTime;
        }
        $timeRage = $this->processingDate($startTime, $endTime);
        //成交单数
        $orders = Db::connection('b2b')->table('user_order')
            ->join('order_status as order_status', 'order_status.ID', 'user_order.ID')
            ->where('user_order.CREATE_TIME', '>=', $startTime)
            ->where('user_order.CREATE_TIME', '<', $endTime)
            ->where('order_status.PAYMENT', 1)
            ->select([
                Db::raw("DATE_FORMAT(my_user_order.CREATE_TIME, '%Y-%m' ) AS `month`"),
                Db::raw('COUNT(DISTINCT my_user_order.ID) AS `count`')
            ])
            ->groupBy([
                'month'
            ])
            ->orderBy('month', 'asc')
            ->get();
        $orders = !empty($orders) ? $orders->toArray() : [];
        //成交客户数
        $users = Db::connection('b2b')->table('user')
            ->join('user_order as user_order', 'user_order.USER_ID', 'user.id')
            ->join('order_status as order_status', 'order_status.ID', 'user_order.ID')
            ->where('user_order.CREATE_TIME', '>=', $startTime)
            ->where('user_order.CREATE_TIME', '<', $endTime)
            ->where('order_status.PAYMENT', 1)
            ->select([
                Db::raw("DATE_FORMAT(my_user_order.CREATE_TIME, '%Y-%m' ) AS `month`"),
                Db::raw('COUNT(DISTINCT my_user.id) AS `count`')
            ])
            ->groupBy([
                'month',
            ])
            ->orderBy('month', 'asc')
            ->get();
        $users = !empty($users) ? $users->toArray() : [];
        return $this->processingData($timeRage, $orders, $users);
    }

    /**
     * 验证规则.
     */
    protected
    function rules(): array
    {
        return [
            'time_enum' => 'in:0,1,2,3',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected
    function messages(): array
    {
        return [
            'time_enum.in' => 'time_enum参数错误',
        ];
    }
}
